<template>
	<view class="custom-album">
		<!-- 单张图片时的特殊展示逻辑 -->
		<view v-if="urls.length === 1" class="single-image-wrapper">
			<image :src="processedUrls[0]._displayUrl" :style="singleImageStyle" mode="widthFix" @load="onImageLoad"
				@error="onImageError" @click.stop="previewImage(processedUrls, 0)">
			</image>
		</view>

		<!-- 多张图片时的网格布局 -->
		<view v-else class="grid-tianzi">
			<view v-for="(file, fileIndex) in processedUrls" :key="fileIndex" class="grid-tianzi-item"
				@click.stop="previewImage(processedUrls, fileIndex)">
				<image :src="file._displayUrl" :lazy-load="true" mode="aspectFill">
				</image>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		name: "custom-album",
		props: {
			urls: {
				type: Array,
				default: () => []
			},
			// 指定用于显示图片的URL字段名
			imageUrlKey: {
				type: String,
				default: 'fileUrl'
			}
		},
		computed: {
			processedUrls() {
				// 更健壮的数据处理逻辑
				return this.urls.filter(item => item && item.fileUrl)
					.map(item => ({
						...item,
						_displayUrl: item[this.imageUrlKey] || item.previewImgUrl || item.fileUrl
					}));
			}
		},
		watch: {
			urls: {
				handler(newVal) {
					if (newVal && newVal.length === 1) {
						// 预先计算单图尺寸，避免加载后的跳变
						this.calculateSingleImageSize();
					}
				},
				immediate: true,
				deep: true
			}
		},
		data() {
			return {
				// 用于单张图片动态样式
				singleImageStyle: {
					width: 'auto',
					height: 'auto',
					opacity: 0
				},
				// 容器的最大尺寸
				maxSingleImageWidth: 450, // 单位 rpx
				maxSingleImageHeight: 600, // 单位 rpx
			};
		},
		methods: {
			// 图片加载完成事件回调
			onImageLoad(e) {
				// 加载完成后显示图片
				this.$set(this, 'singleImageStyle', {
					...this.singleImageStyle,
					opacity: 1
				});
			},

			// 图片加载错误处理
			onImageError() {
				// 出错时也显示图片，避免一直不可见
				this.$set(this, 'singleImageStyle', {
					...this.singleImageStyle,
					opacity: 1
				});
			},

			// 计算单张图片尺寸
			calculateSingleImageSize() {
				if (!this.urls || this.urls.length !== 1) return;

				const imageUrl = this.urls[0][this.imageUrlKey] || this.urls[0].fileUrl;
				if (!imageUrl) return;

				uni.getImageInfo({
					src: imageUrl,
					success: (imageInfo) => {
						const {
							width: originalWidth,
							height: originalHeight
						} = imageInfo;
						const aspectRatio = originalWidth / originalHeight;

						// 将 rpx 转换为 px 进行计算
						const maxWidthPx = uni.upx2px(this.maxSingleImageWidth);
						const maxHeightPx = uni.upx2px(this.maxSingleImageHeight);

						let finalWidth = originalWidth;
						let finalHeight = originalHeight;

						// 等比缩放逻辑
						if (originalWidth > maxWidthPx) {
							finalWidth = maxWidthPx;
							finalHeight = finalWidth / aspectRatio;
						}

						if (finalHeight > maxHeightPx) {
							finalHeight = maxHeightPx;
							finalWidth = finalHeight * aspectRatio;
						}

						// 提前设置尺寸，避免加载后的跳变
						this.$set(this, 'singleImageStyle', {
							width: `${finalWidth}px`,
							height: `${finalHeight}px`,
							opacity: 0 // 保持透明直到加载完成
						});
					},
					fail: () => {
						// 获取失败时使用默认尺寸
						this.$set(this, 'singleImageStyle', {
							width: '200rpx',
							height: '200rpx',
							opacity: 0
						});
					}
				});
			},

			// 图片预览功能
			previewImage(originalFiles, currentIndex) {
				// 使用已处理过的_displayUrl字段，提高兼容性
				const urls = originalFiles.map(file => file._displayUrl || file.fileUrl);

				// 增加有效性检查
				const validUrls = urls.filter(url => url && typeof url === 'string' && url.length > 0);

				if (validUrls.length === 0) {
					console.warn('没有有效的图片URL用于预览');
					return;
				}

				uni.previewImage({
					urls: validUrls,
					current: currentIndex,
					fail: (err) => {
						console.error('图片预览失败:', err);
					}
				});
			},
		}
	}
</script>

<style lang="scss">
	.custom-album {
		display: flex;
		flex-wrap: wrap;
		gap: 10rpx;
	}

	// 单张图片容器样式
	.single-image-wrapper {
		display: inline-block;
		max-width: 100%;

		image {
			border-radius: 8rpx;
			display: block;
			transition: opacity 0.3s ease; // 只对透明度做过渡效果
		}
	}

	.grid-tianzi {
		display: grid;
		grid-template-columns: repeat(3, 1fr);
		grid-auto-rows: 1fr;
		gap: 3px;
		width: 100%;

		.grid-tianzi-item {
			aspect-ratio: 1 / 1;
			overflow: hidden;

			image {
				width: 100%;
				height: 100%;
			}
		}
	}
</style>